<template>
	<view class="content puBgColor4">
		<view
			style="position: fixed;top: 0;width: 100%;display: flex;align-items: center;z-index: 99;flex-direction: column;">
			<view style="height: 10rpx;"></view>
			<view style="width: 100%;display: flex;justify-content: center;;white-space: nowrap;">
				<view
					style="width: 90%;display: flex;margin-top: 60rpx;justify-content: space-between;align-items: center;">
					<view style="width: 50rpx;">
						<uni-icons @click="toUser" type="person" size="25" style="color: #080808;"></uni-icons>
					</view>
					<view style="font-size: 32rpx;flex: 1;text-align: center;overflow: hidden;margin: 0 20rpx;">对话翻译模式
					</view>
					<view style="width: 50rpx;">
						<uni-icons @click="dialogToggle" type="trash" size="25" style="color: #080808;"></uni-icons>
					</view>
				</view>
			</view>

			<view style="width: 90%;display: flex;justify-content: space-between;margin-top: 40rpx;">
				<view
					style="width: 40%;display: flex;flex-direction: column;align-items: center;background-color: #fff;border: 1px solid #7D51FE;border-radius: 50rpx;">
					<view style="height: 10rpx;"></view>
					<view style="width: 80%;">
						<picker @change="bindPickerChange" :value="targetIndex" :range="lanList"
							style="width: 100%;display: flex;justify-content: space-between;">
							<image style="width: 50rpx;margin-right: 10rpx;" src="/static/images/phone.png"
								mode="widthFix">
							</image>

							<view style="display: flex;align-items: center;flex: 1;overflow: hidden;">
								<view
									style="display: flex;font-size: 28rpx;color: #7D51FE;font-weight: bold;white-space: nowrap;flex: 1;overflow: hidden;justify-content: flex-end;">
									{{from.selLan}}
								</view>
								<view style="flex-direction: 0;">
									<uni-icons type="down" size="16"
										style="color: #080808;margin-left: 10rpx;"></uni-icons>
								</view>
							</view>
						</picker>
					</view>
					<view style="height: 10rpx;"></view>
				</view>

				<view @click="exchange"
					style="width: 15%;background-color: aqua;background-color: #7D51FE;display: flex;flex-direction: column;align-items: center;border-radius: 40rpx;justify-content: center;">
					<view style="height: 10rpx;"></view>
					<image src="/static/images/home2.png" style="width: 45rpx;" mode="widthFix"></image>
					<view style="height: 10rpx;"></view>
				</view>

				<view
					style="width: 40%;display: flex;flex-direction: column;align-items: center;background-color: #fff;border: 1px solid #7D51FE;border-radius: 50rpx;">
					<view style="height: 10rpx;"></view>
					<view style="width: 80%;">
						<picker @change="bindPickerChange2" :value="targetIndex2" :range="lanList2"
							style="width: 100%;display: flex;justify-content: space-between;">
							<image style="width: 50rpx;margin-right: 10rpx;" src="/static/images/phone.png"
								mode="widthFix">
							</image>

							<view style="display: flex;align-items: center;flex: 1;overflow: hidden;">
								<view
									style="display: flex;font-size: 28rpx;color: #7D51FE;font-weight: bold;white-space: nowrap;flex: 1;overflow: hidden;justify-content: flex-end;">
									{{from.selLan2}}
								</view>
								<view style="flex-direction: 0;">
									<uni-icons type="down" size="16"
										style="color: #080808;margin-left: 10rpx;"></uni-icons>
								</view>
							</view>
						</picker>
					</view>
					<view style="height: 10rpx;"></view>
				</view>
			</view>
			<view style="height: 10rpx;"></view>
		</view>

		<view style="height: 270rpx;"></view>


		<view v-if="true" style="width: 90%;display: flex;flex-direction: column;align-items: center;">
			<view style="display: block;flex-direction: column;align-items: center;width: 100%;">
				<view style="width: 100%;display: flex;flex-direction: column;">
					<view style="width: 100%;display: flex;margin-bottom: 20rpx;">
						<image v-if="false"
							style="width: 80rpx;height: 80rpx;margin-right: 20rpx;border-radius: 10rpx;flex-shrink: 0;"
							mode="aspectFill">
						</image>
						<image v-else src="/static/images/home4.png"
							style="width: 60rpx;height: 60rpx;margin-right: 20rpx;border-radius: 10rpx;flex-shrink: 0;"
							mode="aspectFill">
						</image>
						<view style="display: flex;max-width: 80%;align-items: center;">
							<view
								style="flex: 1;display: flex;flex-direction: column;background-color: #fff;font-size: 30rpx;border-radius: 20rpx;">
								<view style="flex: 1;white-space: break-spaces;padding: 20rpx; word-break: break-all;">
									<text>你好 请问你来自哪个国家？</text>
								</view>

								<view style="flex: 1;border: 1px solid #f0f0f0;"></view>

								<view style="display: flex;align-items: center;">
									<view
										style="flex: 1;white-space: break-spaces;padding: 20rpx; word-break: break-all;">
										<text>Hello, what country are you from?</text>
									</view>
									<image v-if="true"
										style="width: 30rpx;height: 30rpx;margin-right: 10rpx;flex-shrink: 0;"
										src="../../static/images/playYy3.png" mode="widthFix"></image>
									<image v-else src="../../static/images/playYy4.gif"
										style="width: 30rpx;height: 30rpx;overflow: hidden;margin-right: 10rpx;"
										mode="aspectFit"></image>
								</view>
							</view>
							<image style="width: 40rpx;height: 40rpx;margin-left: 10rpx;flex-shrink: 0;"
								src="/static/images/load.gif" mode="aspectFill"></image>
						</view>
					</view>
					<view style="width: 100%;display: flex;justify-content: flex-end;margin-bottom: 20rpx;">
						<view style="display: flex;max-width: 80%;align-items: center;">
							<image style="width: 40rpx;height: 40rpx;margin-right: 10rpx;flex-shrink: 0;"
								src="/static/images/load.gif" mode="aspectFill"></image>
							<view
								style="flex: 1;display: flex;flex-direction: column;background-color: #fff;font-size: 30rpx;border-radius: 20rpx;">
								<view style="flex: 1;white-space: break-spaces;padding: 20rpx; word-break: break-all;">
									<text>Hello, I'm from the USA</text>
								</view>
								<view style="flex: 1;border: 1px solid #f0f0f0;"></view>

								<view style="display: flex;align-items: center;">
									<view
										style="flex: 1;white-space: break-spaces;padding: 20rpx; word-break: break-all;">
										<text>你好 我来自美国</text>
									</view>
									<image v-if="false"
										style="width: 30rpx;height: 30rpx;margin-right: 10rpx;flex-shrink: 0;"
										src="../../static/images/playYy3.png" mode="widthFix"></image>
									<image v-else src="../../static/images/playYy4.gif"
										style="width: 30rpx;height: 30rpx;overflow: hidden;margin-right: 10rpx;"
										mode="widthFix"></image>
								</view>
							</view>
						</view>
						<image v-if="false"
							style="width: 80rpx;height: 80rpx;margin-left: 20rpx;border-radius: 10rpx;flex-shrink: 0;"
							mode="aspectFill">
						</image>
						<image v-else src="/static/images/home4.png"
							style="width: 60rpx;height: 60rpx;margin-left: 20rpx;border-radius: 10rpx;flex-shrink: 0;"
							mode="aspectFill">
						</image>
					</view>

				</view>
			</view>
		</view>
		<view v-else style="margin: auto;transform: translate(0,-180rpx);display: flex;;flex-direction: column;align-items: center;">
			<image style="width: 450rpx;" mode="widthFix" src="/static/images/home1.png"></image>
			<text style="font-size: 25rpx;margin-top: 40rpx;">点击手机按钮，开始说话</text>
		</view>


		<view
			style="width: 100%;display: flex;position: fixed;bottom: 0;z-index: 9;flex-direction: column;align-items: center;background-color: #F5F6F8;">
			<view style="width: 90%;display: flex;justify-content: space-between;">
				<view @touchstart="startRecord(from.selLan)" @touchend="endRecord" @touchcancel.stop="touchcancelVoice"
					style="width: 45%;display: flex;align-items: center;justify-content: center;border: 2px solid #7D51FE;border-radius: 20rpx;padding: 20rpx 0;">
					<view>
						<uni-icons type="mic" size="22" style="color: #7D51FE;"></uni-icons>
					</view>
					<view style="width: 10rpx;"></view>
					<text style="color: #7D51FE;font-size: 30rpx;font-weight: bold;">{{from.selLan}}</text>
				</view>

				<view @touchstart="startRecord(from.selLan2)" @touchend="endRecord" @touchcancel.stop="touchcancelVoice"
					style="width: 45%;display: flex;align-items: center;justify-content: center;background-color: #7D51FE; border-radius: 20rpx;padding: 20rpx 0;">
					<view>
						<uni-icons type="mic" size="22" style="color: #fff;"></uni-icons>
					</view>
					<view style="width: 10rpx;"></view>
					<text style="color: #fff;font-size: 30rpx;font-weight: bold;">{{from.selLan2}}</text>
				</view>
			</view>
			<view style="height: 20rpx;"></view>
		</view>

		<!-- 退出登录弹窗 -->
		<view>
			<uni-popup ref="alertDialog" type="dialog">
				<uni-popup-dialog type="warn" :cancelText="$t('popup.2')" :confirmText="$t('shop.43')"
					:title="$t('popup.1')" :content="'是否删除对话翻译记录'" @confirm="dialogConfirm"
					@close="dialogClose"></uni-popup-dialog>
			</uni-popup>
		</view>

		<view v-if="voiceFlg"
			style="position: fixed;width: 100%;height: 100vh;background-color: rgba(0, 0, 0, 0.5);z-index: 999;display: flex;">
			<view style=";margin: auto;background-color: #fff;padding: 100rpx;border-radius: 20rpx;">
				<view style="width: 400rpx;height: 40rpx" class="bg1"></view>
				<view style="font-size: 30rpx;width: 100%;text-align: center;margin-top: 60rpx;">{{voiceText}}
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	import {
		host
	} from "@/static/js/config.js";

	import permision from "@/js_sdk/wa-permission/permission.js"
	import methods from "@/utils/methods.js";
	import main from "../../utils/main.js";
	export default {
		data() {
			return {
				token:'',
				//语音
				voiceFlg: false,
				voiceText: '',
				isOpenLyQx: false,
				voiceIndex: -1,
				voiceFlg: false,
				voiceText: 'Hold down to speak',
				voiceTimer: null,
				voiceLength: 0,
				//聊天
				chatDataList: [],
				lanType: '',
				targetIndex: 0,
				targetIndex2: 0,
				from: {
					selLan: '简体中文',
					selLan2: 'English'
				},
				lanList: ['简体中文', 'English'],
				lanList2: ['简体中文', 'English'],
			}
		},
		onLoad() {
			const token = uni.getStorageSync('token');
			this.token = token
			if (!token) {
				uni.redirectTo({
					url: '/pages/login/index?id=-1'
				})
				return
			}
			
			this.initData(1)
			this.getVoiceQx()
			this.voiceFun()
		},
		onHide() {
			if (this.voiceTimer) {
				clearInterval(this.voiceTimer);
				this.voiceTimer = null
				this.voiceLength = 0
			}
		},
		mounted() {
			// let deviceId = '6c40d9514be1a08904ceq4'
			// let type = 'aaaa' 
			// const url = `aipetcare://pages/smallO/homeContent?deviceId=${encodeURIComponent(deviceId)}&type=${encodeURIComponent(type)}`;

			// plus.runtime.openURL(url, (err) => {
			//   if (err) {
			//     uni.showToast({ title: '打开失败', icon: 'none' });
			//   }
			// });

		},
		methods: {
			initData(id) {
				let selLan1_1 = ''
				let selLan2_2 = ''
				if (id == 1) {
					const selLan1 = uni.getStorageSync('selLan')
					const selLan2 = uni.getStorageSync('selLan2')
					this.from.selLan = selLan1 || this.from.selLan
					this.from.selLan2 = selLan2 || this.from.selLan2
				} else {
					selLan1_1 = this.from.selLan
					selLan2_2 = this.from.selLa2
				}


				const index = this.lanList.findIndex(item => item == this.from.selLan )
				const index2 = this.lanList2.findIndex(item => item == this.from.selLan2)
				if (index != -1) {
					this.targetIndex = index
				}
				if (index2 != -1) {
					this.targetIndex2 = index2
				}
			},
			//语音开启
			voiceFun() {
				let self = this
				recorderManager.onStop(function(res) {
					console.log('录音结束2：',res)
					if (self.voiceLength < 1) {
						uni.showToast({
							icon: "none",
							title: '说话时间太短'
						})
					} else {
						console.log('tempFilePath：',res.tempFilePath)
						//self.sendMessageFun(3, res.tempFilePath, true, '')
					}
					self.voiceLength = 0
				});

				recorderManager.onStart(function(res) {
					console.log('开始录音2')
				})

				recorderManager.onPause(function(res) {
					console.log('录音暂停2')
				})

				recorderManager.onError(function(res) {
					console.log('录音报错2')
				})

				innerAudioContext.onPlay(() => {
					console.log('音频播放')
					// if (self.voiceIndex != -1) {
					// 	//self.chatDataList[self.voiceIndex].falg = false
					// 	self.chatDataList.forEach((item, index) => {
					// 		if (index != self.voiceIndex && item.chatType == 3) {
					// 			console.log('index:', index)
					// 			item.falg = true
					// 		} else {
					// 			console.log('index2:', index)
					// 			item.falg = false
					// 		}
					// 	})
					// 	setTimeout(() => {
					// 		console.log('chatDataList3', self.chatDataList)
					// 	}, 2000)
					// }

				})

				innerAudioContext.onPause(() => {
					// if (self.voiceIndex != -1) {
					// 	self.chatDataList[self.voiceIndex].falg = true
					// }
					//console.log('音频暂停')
				})

				innerAudioContext.onStop(() => {
					// if (self.voiceIndex != -1) {
					// 	self.chatDataList[self.voiceIndex].falg = true
					// }
					//console.log('音频停止');
				})
			},
			toPcm(){
				// 1. 读取 MP3 文件（通过 UniApp 选择文件 API 获取）
				uni.chooseFile({
				  type: 'audio',
				  success: async (res) => {
				    const filePath = res.tempFilePaths[0];
				    // 2. 以 ArrayBuffer 格式读取 MP3 文件（获取二进制数据）
				    const arrayBuffer = await new Promise((resolve) => {
				      uni.getFileSystemManager().readFile({
				        filePath,
				        encoding: 'binary', // 读取二进制数据
				        success: (fileRes) => resolve(fileRes.data)
				      });
				    });
				
				    // 3. 初始化 lamejs MP3 解码器
				    const mp3Decoder = new lamejs.Mp3Decoder({
				      mp3Data: new Uint8Array(arrayBuffer), // MP3 二进制数据
				      sampleRate: 44100, // 目标采样率（需与 MP3 实际采样率匹配，可通过库自动识别）
				      channels: 1 // 声道数（1=单声道，2=双声道，需匹配 MP3 实际参数）
				    });
				
				    // 4. 解码 MP3 为 PCM 数据（16bit 整型 PCM）
				    const pcmArray = mp3Decoder.decode(); // 返回 Uint16Array 格式的 PCM 数据
				
				    // 5. （可选）将 PCM 保存为本地文件（如 .pcm 后缀）
				    uni.getFileSystemManager().writeFile({
				      filePath: `${uni.env.USER_DATA_PATH}/output.pcm`,
				      data: pcmArray,
				      encoding: 'binary',
				      success: () => uni.showToast({ title: 'PCM 转换成功' })
				    });
				  }
				});
			},
			getVoiceQx() {
				let self = this
				if (self.$store.state.platform == 'android') {
					self.requestAndroidPermission('android.permission.RECORD_AUDIO')
				} else {
					self.isOpenLyQx = true
					// const falg = permision.judgeIosPermission("record")
					// if (falg) {
					// 	//有权限
					// 	self.isOpenLyQx = true
					// }
				}
			},
			async requestAndroidPermission(permisionID) {
				var result = await permision.requestAndroidPermission(permisionID)
				var strStatus
				if (result == 1) {
					this.isOpenLyQx = true
				} else if (result == 0) {
					uni.showToast({
						icon: 'none',
						title: '请开启录音权限'
					});
				} else {
					uni.showToast({
						icon: 'none',
						title: '请开启录音权限'
					});
				}

			},
			startRecord(lanType) {
				this.lanType = lanType
				this.stopVoice()
				// if (!this.isSuccess) {
				// 	uni.showToast({
				// 		icon: 'none',
				// 		title: '正在思考中，请停止思考！'
				// 	})
				// 	return
				// }
				if (this.isOpenLyQx) {
					this.selLanFun(lanType)

					this.voiceFlg = true
					this.voiceTimer = setInterval(() => {
						this.voiceLength += 1
					}, 1000)
					recorderManager.start()
				} else {
					if (this.$store.state.platform == 'android') {
						this.requestAndroidPermission('android.permission.RECORD_AUDIO')
					} else {
						this.isOpenLyQx = true
						// const falg = permision.judgeIosPermission("record")
						// if (falg) {
						// 	//有权限
						// 	this.isOpenLyQx = true
						// }
					}
				}
			},
			stopVoice(index) {
				this.voiceIndex = index
				innerAudioContext.pause();
			},
			selLanFun(lanType) {
				switch (lanType) {
					case '简体中文':
						this.voiceText = '松开发送'
						break;
					case 'English':
						this.voiceText = 'Release send'
						break;
				}
			},
			playVoice(url, index) {
				///static/Gw(1).mp3
				if (!url) {
					uni.showToast({
						icon: 'none',
						title: '请稍等再试，语音生成中...'
					})
					return
				}
				this.voiceIndex = index
				if (url) {
					innerAudioContext.src = url
					innerAudioContext.play();
				}
			},
			endRecord() {
				this.voiceFlg = false
				// this.voiceText = '录音结束'
				setTimeout(() => {
					recorderManager.stop()
				}, 500)
				clearInterval(this.voiceTimer);
				this.voiceTimer = null

			},
			touchcancelVoice() {},
			//语音结束
			exchange() {

				let oldSelLan = this.from.selLan
				let oldSelLan2 = this.from.selLan2

				this.from.selLan = oldSelLan2
				this.from.selLan2 = oldSelLan
				uni.setStorageSync('selLan', this.from.selLan)
				uni.setStorageSync('selLan2', this.from.selLan2)
				this.initData()
			},
			bindPickerChange: function(e) {
				let oldSelLan = this.from.selLan
				this.targetIndex = e.detail.value
				this.from.selLan = this.lanList[e.detail.value]
				uni.setStorageSync('selLan', this.from.selLan)
				if (this.from.selLan == this.from.selLan2) {
					this.from.selLan2 = oldSelLan
					uni.setStorageSync('selLan2', this.from.selLan2)
					this.initData()
				}
			},
			bindPickerChange2: function(e) {
				let oldSelLan = this.from.selLan2
				this.targetIndex2 = e.detail.value
				this.from.selLan2 = this.lanList[e.detail.value]
				uni.setStorageSync('selLan2', this.from.selLan2)
				if (this.from.selLan2 == this.from.selLan) {
					this.from.selLan = oldSelLan
					uni.setStorageSync('selLan', this.from.selLan)
					this.initData()
				}
			},
			dialogToggle() {
				this.$refs.alertDialog.open()
			},
			dialogConfirm() {
				this.logout()
			},
			dialogClose() {},
			toUser(){
				uni.navigateTo({
					url:'/pages/user/index'
				})
			}
		}
	}
</script>

<style lang="scss">
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		min-height: 100vh;
		background: linear-gradient(to bottom, #DFD7F9 0px, #f2f0f9 398rpx, #F5F6F8 100%)
	}

	.bg1 {
		background-image: url('~@/static/images/palyYy.gif');
		background-position: center;
		background-size: 100%;
		background-repeat: no-repeat;
	}
</style>